<template>
	<!-- 
		1.手机蓝牙打开
		2.微信也许访问蓝牙和位置信息
		3.重启蓝牙设备
		4.不行的时候,删掉手机中蓝牙,重新链接 
		-->
	<view class="content">
		<button size="mini" type="primary" @tap="startBluetoothDeviceDiscovery">搜索周边设备</button>
		<button size="mini" type="warn" @tap="stopBluetoothDevicesDiscovery">停止搜索</button>
		<!-- <button size="mini" type="primary" @tap="notify">监听</button> -->
		<view></view>
		<button size="mini" type="primary" @tap="sendTEMPERATURE">测温度</button>
		<button size="mini" type="primary" @tap="sendROTATING_SPEED">测转速</button>
		<button size="mini" type="primary" @tap="sendVIBRATION_JSD">加速度</button>
		<button size="mini" type="primary" @tap="sendVIBRATION_SD">测速度</button>
		<button size="mini" type="primary" @tap="sendVIBRATION_WY">测位移</button>
		<button size="mini" type="warn" @tap="stopSend">停止发送</button>

		<scroll-view class="device_list" scroll-y="true" show-scrollbar="true">
			<radio-group>
				<view v-for="(item,index) in devicesList" :key="index" class="device_item">
					<view style="font-size: 32rpx; color: #333;">
						<radio :value="item.deviceId" @tap="select_deviceId(item)" />{{item.localName }}
					</view>
					<view style="font-size: 20rpx">信号强度: {{item.RSSI}}dBm ({{Math.max(100+item.RSSI,0)}}%)</view>
					<view style="font-size: 20rpx">deviceId: {{item.deviceId}}</view>
					<view v-if="item.advertisServiceUUIDs" style="font-size: 20rpx">Service数量:
						{{item.advertisServiceUUIDs.length || 0}}
					</view>

					<radio-group v-if="deviceId===item.deviceId">
						<view v-for="(service,service_index) in serviceList" :key="service_index"
							style="font-size: 20rpx">
							<radio style="transform:scale(0.7)" :value="service.uuid" @tap="select_service(service)" />
							{{service.uuid }}
						</view>
					</radio-group>
				</view>
			</radio-group>
		</scroll-view>
		<view>{{ message }}</view>
	</view>
</template>
<script>
	import {
		ROTATING_SPEED,
		TEMPERATURE,
		VIBRATION_JSD,
		VIBRATION_SD,
		VIBRATION_WY,
		parseResultValue
	} from './as1000.js';
	import Bluetooth from './bluetooth.js'
	import {
		ab2hex,
		hexCharCodeToStr
	} from './utils.js';




	export default {
		data() {
			const bluetooth = new Bluetooth();
			return {
				bluetooth,
				isOpenBle: false, //是否已经打开蓝牙，默认为false
				devicesList: [], //设备列表
				serviceList: [], //服务列表
				deviceId: "", //选中的deviceId
				// 监听到的内容
				message: '',
				messageHex: ''
			}
		},
		//页面卸载是关闭蓝牙链接
		onUnload() {
			this.bluetooth.closeBLEConnection();
			this.bluetooth.closeBluetoothAdapter();
		},
		//页面打开,获取位置,打开蓝牙链接
		onLoad() {
			const that = this
			wx.getLocation({
				type: 'gcj02',
				success(res) {
					console.log(res)
					that.bluetooth.openBluetoothAdapter();
				}
			})
		},
		methods: {

			//搜索周边设备
			startBluetoothDeviceDiscovery() {
				uni.showLoading({
					title: '蓝牙搜索中'
				})

				let self = this;
				self.devicesList = [];

				setTimeout(() => {
					uni.startBluetoothDevicesDiscovery({
						success: res => {
							uni.onBluetoothDeviceFound(devices => {
								//不重复,就添加到devicesList中,
								const firstDevice = devices.devices[0]
								if (!self.devicesList.some(item => {
										return item.deviceId === firstDevice
											.deviceId
									})) {
									// 有设备且可以连接状态且有服务uuid才显示
									if (firstDevice.connectable && firstDevice.localName &&
										firstDevice.advertisServiceUUIDs?.length > 0) {
										console.log("发现设备: " + JSON.stringify(devices));
										self.devicesList.push(firstDevice)

										// 测试获取mac地址
										const s1 = ab2hex(firstDevice
											.advertisData)
										const s2 = hexCharCodeToStr(s1)
										var buff = firstDevice.advertisData.slice(2, 8);
										var arrayBuff = Array.prototype.map.call(
											new Uint8Array(buff), x => ('00' +
												x.toString(16)).slice(-2)).join(':');
										var arrayMac = arrayBuff.toUpperCase();
										console.log("advertisData: ", firstDevice
											.advertisData, s1, s2, arrayMac);
									}
								}
							});
						},
						fail: err => {
							console.log(`搜索设备失败` + JSON.stringify(err));
						}
					})
				}, 200)
			},

			//停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery() {
				uni.hideLoading();
				this.bluetooth.stopBluetoothDevicesDiscovery();
			},


			//选中设备
			async select_deviceId(item) {
				this.deviceId = item.deviceId;
				this.bluetooth.deviceId = item.deviceId;
				uni.setStorageSync('deviceId', this.bluetooth.deviceId);

				this.serviceList = [];

				try {
					//1.链接设备
					let result = await this.bluetooth.createBLEConnection();
					//2.寻找服务
					let result2 = await this.bluetooth.getBLEDeviceServices();

					console.log("获取服务: " + JSON.stringify(result2));

					this.serviceList = result2;
				} catch (e) {
					//TODO handle the exception
					console.log("e: " + JSON.stringify(e));
				}
			},

			//选中服务
			async select_service(res) {

				this.bluetooth.serviceId = res.uuid;
				uni.setStorageSync('serviceId', res.uuid);

				try {
					let result = await this.bluetooth.getBLEDeviceCharacteristics();
				} catch (e) {
					//TODO handle the exception
					console.log("e: " + JSON.stringify(e));
				}

			},



			// 测温度
			sendTEMPERATURE() {
				// 向蓝牙设备发送一个0x00的16进制数据
				// let msg = 'hello'
				// const buffer = new ArrayBuffer(msg.length)
				// const dataView = new DataView(buffer)
				// // dataView.setUint8(0, 0)
				// for (var i = 0; i < msg.length; i++) {
				// 	dataView.setUint8(i, msg.charAt(i).charCodeAt())
				// }

				this.stop = false
				this.sendStart(TEMPERATURE, 1)

			},

			// 测试速度
			sendROTATING_SPEED() {
				this.stop = false
				this.sendStart(ROTATING_SPEED, 2)
			},

			// 测试速度
			sendVIBRATION_JSD() {
				this.stop = false
				this.sendStart(VIBRATION_JSD, 3)
			},

			// 测试速度
			sendVIBRATION_SD() {
				this.stop = false
				this.sendStart(VIBRATION_SD, 4)
			},

			// 测试速度
			sendVIBRATION_WY() {
				this.stop = false
				this.sendStart(VIBRATION_WY, 5)
			},

			sendStart(data, type) {
				const self = this
				console.log('sendStart', data, type)
				const arrayBuffer = new Uint8Array(data)
				// 监听notify
				this.bluetooth.notifyBLECharacteristicValue(bytes => {
					const result = parseResultValue(type, bytes)
					self.message = result
					self.$nextTick(() => {
						!self.stop && self.sendStart(data, type)
					})
				});
				// 写入write
				this.bluetooth.writeBLECharacteristicValue(arrayBuffer.buffer)
			},

			stopSend() {
				this.stop = true
			}
		},
	}
</script>

<style>

</style>